<template>
    <el-dialog v-model="show" title="充值预付款" width="35%" align-center @close="handleClose">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
            status-icon>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="所属公司:" prop="companyId">
                        <el-select @change="selectChange" :disabled="typeShow" style="width: 100%;"
                            v-model="ruleForm.companyId" placeholder="请选择所属公司">
                            <el-option v-for="item in props.subsidiariesList" :key="item.id" :label="item.companyName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户名称:" prop="customerId">
                        <el-select style="width: 100%;" :disabled="typeShow" v-model="ruleForm.customerId"
                            placeholder="请选择客户名称">
                            <el-option v-for="item in customerList" :key="item.id" :label="item.customer_name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="收款日期:" prop="collectDate">
                        <el-date-picker v-model="ruleForm.collectDate" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                            type="date" placeholder="请选择收款日期" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="付款方式:" prop="collectMethod">
                        <el-select style="width: 100%;" v-model="ruleForm.collectMethod" placeholder="请选择付款方式">
                            <el-option v-for="item in pay_type" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="收款账号:" prop="collectAccountId">
                        <el-select v-model="ruleForm.collectAccountId" style="width: 100%;" placeholder="请选择收款账号">
                            <el-option v-for="item in paymentCard" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="Number(ruleForm.collectMethod) == 1">
                    <el-form-item label="付款单号:" prop="paymentOrderCode">
                        <el-input v-model="ruleForm.paymentOrderCode" placeholder="请输入付款单号" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="Number(ruleForm.collectMethod) == 2">
                    <el-form-item label="付款人:" prop="payerName">
                        <el-input v-model="ruleForm.payerName" placeholder="请输入付款人" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="收款金额:" prop="collectAmount">
                        <el-input v-model.number="ruleForm.collectAmount" placeholder="请输入收款金额" />
                    </el-form-item>
                </el-col>
                <el-col :span="24" class="mb20">
                    <div style="color: red;">在同日期下有3笔价格相同的付款信息，请慎重核对后在进行审核<strong>查看具体信息</strong> </div>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="收款信息:" prop="collectInfo">
                        <el-input v-model="ruleForm.collectInfo" placeholder="请输入收款信息" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="凭证上传:" prop="fileUrl">
                        <el-upload ref="designSketchRef" :show-file-list="false" drag :action="uploadImgUrl"
                            :headers="headers" multiple :auto-upload="true" :on-success="handleDesignSketchSuccess"
                            :before-upload="beforedeSignSketchUpload">
                            <img style="height: 100px;" v-if="ruleForm.fileUrl" :src="ruleForm.fileUrl" />
                            <template v-else>
                                <div style="padding-top: 10px;">
                                    <uploadStyle type="1" icon="PictureFilled" />
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" v-loading="loading" @click="handleSubmit(ruleFormRef)">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { globalHeaders } from "@/utils/request";
import uploadStyle from '@/views/productManagement/designerTakesOrders/components/uploadStyle.vue';
import { getPaymentCardByCompanyIdApi } from '@/api/sj/financialManagement/paymentCard';
import { addAdvanceChargeApi, getCustomerListByCompanyIdApi } from '@/api/sj/financialManagement/advancePaymentManagement'


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList', 'type', 'subsidiariesList']);
const emits = defineEmits(['submit', 'close']);
const { pay_type } = toRefs<any>(proxy?.useDict('pay_type'));


const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);

const show = ref(false);
const dialogVisible = ref();
const paymentCard = ref<any>([]);
const loading = ref(false);
const customerList = ref<any>([]);
const typeShow = ref(false);


watch(() => props.visible, async (newValue) => {
    show.value = newValue
    if (newValue) {

        if (props.initList.companyId) {
            typeShow.value = true;
            ruleForm.companyId = Number(props.initList.companyId) || null
            selectChange(Number(props.initList.companyId));
            ruleForm.customerId = props.initList.customerId || null
        } else {
            ruleForm.customerId = null;
            ruleForm.companyId = null;
            typeShow.value = false;
            ruleFormRef.value?.resetFields();
        }
    }
}, { deep: true });



interface RuleForm {
    paymentOrderCode: string
    collectAccountId: number | null
    collectMethod: string
    collectDate: string
    fileUrl: string
    collectInfo: string
    payerName: string
    collectAmount: null | number
    companyId: number | null
    customerId: null | number
};
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    paymentOrderCode: '', // 付款单号
    collectAccountId: null, // 收款账号
    collectMethod: '', // 付款方式
    collectDate: '', // 收款时间
    fileUrl: '', // 收款凭证
    collectInfo: '', // 收款信息
    payerName: '', // 付款人
    collectAmount: null, // 收款金额
    companyId: null, // 公司id
    customerId: null, // 客户id
});

const rules = reactive<FormRules>({
    payerName: [
        { required: true, message: '请输入付款人', trigger: 'blur' },
    ],
    collectAmount: [
        { required: true, message: '请输入收款金额', trigger: 'blur' },
        { type: 'number', min: 0, message: '收款金额必须为数字值' }
    ],
    paymentOrderCode: [
        { required: true, message: '请输入付款单号', trigger: 'blur' },
    ],
    fileUrl: [
        { required: true, message: '请上传凭证', trigger: 'blur' },
    ],
    companyId: [
        {
            required: true,
            message: '请选择所属公司',
            trigger: ['blur', 'change'],
        },
    ],
    customerId: [
        {
            required: true,
            message: '请选择客户',
            trigger: ['blur', 'change'],
        },
    ],
    collectDate: [
        {
            required: true,
            message: '请选择收款日期',
            trigger: ['blur', 'change'],
        },
    ],
    collectMethod: [
        {
            required: true,
            message: '请选择付款方式',
            trigger: ['blur', 'change'],
        },
    ],
    collectAccountId: [
        {
            required: true,
            message: '请选择收款账号',
            trigger: ['blur', 'change'],
        },
    ],
});

/** 上传效果图 */
const handleDesignSketchSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    dialogVisible.value.close();

    ruleForm.fileUrl = response.data.url;
};

const beforedeSignSketchUpload: UploadProps['beforeUpload'] = () => {
    dialogVisible.value = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
};

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true;
            try {
                const { code } = await addAdvanceChargeApi({
                    ...ruleForm,
                })
                if (code == 200) {
                    proxy?.$modal.msgSuccess('操作成功');
                    emits('submit', true);
                    loading.value = false;
                    handleClose();
                }
            } catch (error) {
                loading.value = false;
            }
        } else {
            console.log('error submit!', fields)
        }
    })
};


const handleClose = () => {
    ruleFormRef.value?.resetFields();
    emits('close');
};

/** 选择所属公司 获取该公司下的 充值卡 */
const selectChange = async (e: number) => {
    try {
        const { data } = await getPaymentCardByCompanyIdApi(e)

        paymentCard.value = data
    } catch (error) {

    }

    try {
        const { data } = await getCustomerListByCompanyIdApi(e)

        customerList.value = data

    } catch (error) {

    }
};

onMounted(() => {
})
</script>

<style lang="scss" scoped>
::v-deep .el-upload-dragger {
    padding: 0px 4px !important;
    height: 100px !important;
    width: 260px;
}

::v-deep .el-divider--horizontal {
    margin: 12px 0;
}
</style>